package com.anosine.gpsl.android.ui.fragment;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import android.annotation.SuppressLint;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.NotificationCompat;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.TextView;

import com.anosine.gpsl.android.AppConstants;
import com.anosine.gpsl.android.GPSLApp;
import com.anosine.gpsl.android.R;
import com.anosine.gpsl.android.WebConstants;
import com.anosine.gpsl.android.alarm.ServiceUtil;
import com.anosine.gpsl.android.base.BaseFragment;
import com.anosine.gpsl.android.entity.Active;
import com.anosine.gpsl.android.entity.ActiveList;
import com.anosine.gpsl.android.entity.GeocoderBean;
import com.anosine.gpsl.android.entity.Login;
import com.anosine.gpsl.android.entity.PushMessageBean;
import com.anosine.gpsl.android.entity.RegionListOfPagerBean;
import com.anosine.gpsl.android.entity.RegionListOfPagerList;
import com.anosine.gpsl.android.presenter.ActivieListPresenter;
import com.anosine.gpsl.android.ui.ActiveListView;
import com.anosine.gpsl.android.ui.activity.GPSLMainActivity;
import com.anosine.gpsl.android.util.HttpRequestListener;
import com.anosine.gpsl.android.util.SendHttpUtils;
import com.anosine.gpsl.android.util.ToastHelper;
import com.anosine.gpsl.android.util.UserInfoProxy;
import com.anosine.gpsl.android.util.ormdb.DaoHelper;
import com.anosine.gpsl.android.widget.MarqueeTextView;
import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.SDKInitializer;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BaiduMap.OnMyLocationClickListener;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.InfoWindow;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.Marker;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.MyLocationConfiguration;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.map.OverlayOptions;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.utils.CoordinateConverter;
import com.baidu.mapapi.utils.CoordinateConverter.CoordType;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.reflect.TypeToken;
import com.lidroid.xutils.http.RequestParams;

public class TabMonitoringFragmentNew extends BaseFragment implements
		ActiveListView {// implements ActiveListView
	private boolean isFirstLoc = true;// 是否首次定位
	private MapView mMvShow;
	private BaiduMap mBmShow;

	private Handler mHandler = new Handler();
	// 定位相关
	private LocationClient mLocClient;
	private MyLocationListenner myListener = new MyLocationListenner();
	private BitmapDescriptor bdA;
	private Active mActiveCarBean;
	private LatLng mMyLocation;
	private InfoWindow mInfoWindow;

	private String status;
	// 播放声音
	public static MediaPlayer player;
	public static int isPlayer = 0;// 0未启动 1已播放
	String address = null;
	LatLng Newll;
	String titleMessage, dateMessage;
	private DaoHelper<PushMessageBean> pushMessageDao;
	MarqueeTextView State_Title;
	TextView address_tv, tv_alarm;
	private final List<RegionListOfPagerBean> mList = new ArrayList<RegionListOfPagerBean>();
	private List<Active> mActive = new ArrayList<Active>();
	String getOid;

	/**
	 * 方法名：onCreateView(LayoutInflater inflater, ViewGroup container, Bundle
	 * savedInstanceState) 功 能：创建该Fragment的视图 参 数：LayoutInflater inflater
	 * LayoutInflater是用来找res/layout/下的xml布局文件，并且实例化 ViewGroup container
	 * ViewGroup是Layout的基类, Bundle savedInstanceState 返回值： View view 视图
	 */
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		SDKInitializer.initialize(getActivity().getApplicationContext());
		View view = inflater.inflate(R.layout.fragment_main_tab_monitoring,
				null);
		pushMessageDao = new DaoHelper<PushMessageBean>(getActivity(),
				PushMessageBean.class);
		State_Title = (MarqueeTextView) view.findViewById(R.id.marquee_title);
		address_tv = (TextView) view.findViewById(R.id.tv_address);
		tv_alarm = (TextView) view.findViewById(R.id.tv_alarm);
		bdA = BitmapDescriptorFactory
				.fromResource(R.drawable.icon_gcoding_phone);
		mMvShow = (MapView) view.findViewById(R.id.mv_baidu_monitor);
		// 地图初始化
		mBmShow = mMvShow.getMap();
		getOid = getArguments().getString("oid");
		monitorFragment = this;
		userInfo = UserInfoProxy.getInstance().getLoginInfo();
		return view;
	}

	// 地点标点显示
	private Marker[] mMarker, popMarker, popMarkerCarTitle;
	TextView[] button, button1;
	boolean[] SelectBtn;
	View view_alert, name_alert, carTitle_alert;
	InfoWindow.OnInfoWindowClickListener listener = null;

	private void getAdCoordinate() {
		// Login userInfo = UserInfoProxy.getInstance().getLoginInfo();
		String url = String.format("%1s/%2s", AppConstants.sCommonUrl,
				WebConstants.Do_GetRegionListOfPage_Action);
		RequestParams params = new RequestParams();
		params.addBodyParameter("usermd5", userInfo.userMd5);

		SendHttpUtils sendHttp = new SendHttpUtils();
		TypeToken type = new TypeToken<RegionListOfPagerList>() {
		};
		sendHttp.doRequest(url, params, type,
				new HttpRequestListener<RegionListOfPagerList>() {
					@Override
					public void onSuccess(String result, RegionListOfPagerList t) {

						JsonObject object = new JsonParser().parse(result)
								.getAsJsonObject();
						JsonArray jsonArray = object.get("rows")
								.getAsJsonArray();
						for (int i = 0; i < jsonArray.size(); i++) {
							JsonObject temp = jsonArray.get(i)
									.getAsJsonObject();
							RegionListOfPagerBean message = new RegionListOfPagerBean();
							message.maxlat = (temp.get("maxlat").getAsString());
							message.maxlon = (temp.get("maxlon").getAsString());
							message.regionname = (temp.get("regionname")
									.getAsString());
							message.regioninfo = (temp.get("regioninfo")
									.getAsString());
							mList.add(message);

						}
						// /////////////////////////////////
						SelectBtn = new boolean[mList.size()];
						button = new TextView[mList.size()];
						button1 = new TextView[mList.size()];
						// //////////////////////////////////////

					}

					@Override
					public void onFailure(String error) {
						ToastHelper.toast(error);
					}
				});

	}

	/**
	 * 设置所有添加地址的坐标点, pop
	 */
	@SuppressLint("ResourceAsColor")
	public void initOverlay(List<RegionListOfPagerBean> list) {
		// 坐标点
		mMarker = new Marker[list.size()];
		popMarker = new Marker[list.size()];
		// 坐标定义 经纬度
		LatLng[] latLng = new LatLng[list.size()];
		// 标点图片
		BitmapDescriptor bd;
		for (int i = 0; i < list.size(); i++) {
			// 坐标 经纬度Double.parseDouble
			latLng[i] = new LatLng(
					Double.parseDouble(list.get(i).maxlat) / 1000000,
					Double.parseDouble(list.get(i).maxlon) / 1000000);
			// 在此矫正位置
			// 将GPS设备采集的原始GPS坐标转换成百度坐标
			CoordinateConverter converter = new CoordinateConverter();
			converter.from(CoordType.GPS);
			// sourceLatLng待转换坐标
			converter.coord(latLng[i]);
			LatLng desLatLng = converter.convert();

			// 坐标图片
			bd = BitmapDescriptorFactory.fromResource(R.drawable.icon_gcoding);// 自动添加的地址
			// 坐标点
			OverlayOptions oob = new MarkerOptions().position(desLatLng)
					.icon(bd).zIndex(9).draggable(true).anchor(1.0f, 1.0f);

			mMarker[i] = (Marker) (mBmShow.addOverlay(oob));

			name_alert = LayoutInflater.from(getActivity()).inflate(
					R.layout.fragment_monitor_marker_name, null);
			TextView name = (TextView) name_alert.findViewById(R.id.name);
			name.setText("\t" + list.get(i).regionname + "\t");
			OverlayOptions oobb = new MarkerOptions()
					.position(desLatLng)
					.icon(BitmapDescriptorFactory
							.fromBitmap(getViewBitmap(name_alert))).zIndex(9)
					.draggable(true).anchor(0f, 1.0f);// 1.0
			popMarker[i] = (Marker) (mBmShow.addOverlay(oobb));

		}
	}

	private Bitmap getViewBitmap(View addViewContent) {

		addViewContent.setDrawingCacheEnabled(true);

		addViewContent.measure(View.MeasureSpec.makeMeasureSpec(0,
				View.MeasureSpec.UNSPECIFIED), View.MeasureSpec
				.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
		addViewContent.layout(0, 0, addViewContent.getMeasuredWidth(),
				addViewContent.getMeasuredHeight());

		addViewContent.buildDrawingCache();
		Bitmap cacheBitmap = addViewContent.getDrawingCache();
		Bitmap bitmap = Bitmap.createBitmap(cacheBitmap);

		return bitmap;
	}

	private LatLng getGpsToBaidu(LatLng latLng) {
		// 在此矫正位置
		// 将GPS设备采集的原始GPS坐标转换成百度坐标
		CoordinateConverter converter = new CoordinateConverter();
		converter.from(CoordType.GPS);
		// sourceLatLng待转换坐标
		converter.coord(latLng);
		LatLng desLatLng = converter.convert();
		return desLatLng;
	}

	private void initData() {
		// 开启定位图层
		mBmShow.setMyLocationEnabled(true);
		// 定位初始化
		mLocClient = new LocationClient(getActivity());
		mLocClient.registerLocationListener(myListener);
		LocationClientOption option = new LocationClientOption();
		option.setOpenGps(true);// 打开gps
		option.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy);
		option.setCoorType("bd09ll"); // 设置坐标类型
		option.setScanSpan(10000);// 设置发起定位请求的间隔时间为15000ms
		option.setIsNeedAddress(true);
		mLocClient.setLocOption(option);
		mLocClient.start();
		// 地图中心点的点击事件
		mBmShow.setOnMyLocationClickListener(new OnMyLocationClickListener() {

			@Override
			public boolean onMyLocationClick() {
				// 显示车的地址
				Newll = getGpsToBaidu(new LatLng(
						Double.valueOf(mActive.get(0).lt), Double
								.valueOf(mActive.get(0).lo)));
				if (Double.valueOf(mActive.get(0).lo) == 0.0
						|| Double.valueOf(mActive.get(0).lt) == 0.0) {
					address_tv.setVisibility(View.GONE);
				} else {
					address = goGeocoder(Newll, 999, 0);
					if ("".equals(address) || address == null) {
						address_tv.setVisibility(View.VISIBLE);
						address_tv.setText("车辆地址正在定位，请稍候");
					} else {
						address_tv.setVisibility(View.VISIBLE);
						address_tv.setText("车在：" + address);
					}
				}
				return false;
			}
		});
		mBmShow.setOnMarkerClickListener(new BaiduMap.OnMarkerClickListener() {
			@SuppressLint("ResourceAsColor")
			public boolean onMarkerClick(final Marker marker) {
				if (mActive.size() > 0) {
					for (int m = 0; m < mActive.size(); m++) {
						if (marker == mMarkerCar[m]) {
							// 显示车的地址
							Newll = getGpsToBaidu(new LatLng(Double
									.valueOf(mActive.get(m).lt), Double
									.valueOf(mActive.get(m).lo)));
							if (Double.valueOf(mActive.get(m).lo) == 0.0
									|| Double.valueOf(mActive.get(m).lt) == 0.0) {
								address_tv.setVisibility(View.GONE);
							} else {
								address = goGeocoder(Newll, 999, 0);

								if ("".equals(address) || address == null) {// 此处address.equals("")出错，空指针异常
									address_tv.setVisibility(View.VISIBLE);
									address_tv.setText("车辆地址正在定位，请稍候");
								} else {
									address_tv.setVisibility(View.VISIBLE);
									address_tv.setText("车在：" + address);
								}
							}
						}
					}

				}
				if (mList.size() > 0) {

					for (int i = 0; i < mList.size(); i++) {

						if (marker == popMarker[i]) {
							SelectBtn[i] = true;
							for (int j = 0; j < mList.size(); j++) {
								if (i != j) {
									SelectBtn[j] = false;
								}
							}
							view_alert = LayoutInflater
									.from(getActivity())
									.inflate(
											R.layout.activity_main_tab_monitoring_alter_view,
											null);
							button[i] = (TextView) view_alert
									.findViewById(R.id.title);
							button1[i] = (TextView) view_alert
									.findViewById(R.id.info_content);
							button[i].setTextSize(12);
							button1[i].setTextSize(12);
							button[i].setText(mList.get(i).regionname);
							view_alert.setTag(i + "");
							button[i].setOnClickListener(new OnClickListener() {

								@Override
								public void onClick(View arg0) {
									mBmShow.hideInfoWindow();
									// 把所有marker弹出框标记设成false
									for (int m = 0; m < mList.size(); m++) {
										SelectBtn[m] = false;
									}
								}
							});
							Pattern p = Pattern.compile("[0-9]*");
							Matcher m = p.matcher(mList.get(i).regioninfo);

							if (m.matches()
									&& !("".equals(mList.get(i).regioninfo) || null == mList
											.get(i).regioninfo)) {

								button1[i].setText("点击拨打："
										+ mList.get(i).regioninfo);
								// 是数字
								button1[i]
										.setOnClickListener(new OnClickListener() {

											@Override
											public void onClick(View arg0) {
												String position = (String) view_alert
														.getTag();
												// 用intent启动拨打电话
												Intent intent = new Intent(
														Intent.ACTION_CALL,
														Uri.parse("tel:"
																+ mList.get(Integer
																		.parseInt(position)).regioninfo));
												startActivity(intent);
											}
										});
							} else {
								button1[i].setText(mList.get(i).regioninfo);
								// 不是数字
								button1[i]
										.setOnClickListener(new OnClickListener() {

											@Override
											public void onClick(View arg0) {

												mBmShow.hideInfoWindow();
												for (int m = 0; m < mList
														.size(); m++) {
													SelectBtn[m] = false;
												}
											}
										});
							}

							LatLng ll = marker.getPosition();
							mInfoWindow = new InfoWindow(view_alert, ll, -47);
							mBmShow.showInfoWindow(mInfoWindow);
						}

						if (marker == mMarker[i]) {
							SelectBtn[i] = true;
							for (int j = 0; j < mList.size(); j++) {
								if (i != j) {
									SelectBtn[j] = false;
								}
							}
							view_alert = LayoutInflater
									.from(getActivity())
									.inflate(
											R.layout.activity_main_tab_monitoring_alter_view,
											null);
							button[i] = (TextView) view_alert
									.findViewById(R.id.title);
							button1[i] = (TextView) view_alert
									.findViewById(R.id.info_content);
							button[i].setTextSize(12);
							button1[i].setTextSize(12);
							button[i].setText(mList.get(i).regionname);
							view_alert.setTag(i + "");
							button[i].setOnClickListener(new OnClickListener() {

								@Override
								public void onClick(View arg0) {
									mBmShow.hideInfoWindow();
									// 把所有marker弹出框标记设成false
									for (int m = 0; m < mList.size(); m++) {
										SelectBtn[m] = false;
									}
								}
							});
							Pattern p = Pattern.compile("[0-9]*");
							Matcher m = p.matcher(mList.get(i).regioninfo);

							if (m.matches()
									&& !("".equals(mList.get(i).regioninfo) || null == mList
											.get(i).regioninfo)) {

								button1[i].setText("点击拨打："
										+ mList.get(i).regioninfo);
								// 是数字
								button1[i]
										.setOnClickListener(new OnClickListener() {

											@Override
											public void onClick(View arg0) {
												String position = (String) view_alert
														.getTag();
												// 用intent启动拨打电话
												Intent intent = new Intent(
														Intent.ACTION_CALL,
														Uri.parse("tel:"
																+ mList.get(Integer
																		.parseInt(position)).regioninfo));
												startActivity(intent);
											}
										});
							} else {
								button1[i].setText(mList.get(i).regioninfo);
								// 不是数字
								button1[i]
										.setOnClickListener(new OnClickListener() {

											@Override
											public void onClick(View arg0) {

												mBmShow.hideInfoWindow();
												for (int m = 0; m < mList
														.size(); m++) {
													SelectBtn[m] = false;
												}
											}
										});
							}

							LatLng ll = marker.getPosition();
							mInfoWindow = new InfoWindow(view_alert, ll, -47);// pop[i]
																				// listener
							mBmShow.showInfoWindow(mInfoWindow);
						}
					}
				}
				return true;
			}
		});
	}

	Login userInfo;

	public void sendGetHttpPositon() {
		Log.i("TAGTimer", "sendGetHttpPositon");
		ActivieListPresenter presenter = new ActivieListPresenter(
				monitorFragment);
		// userInfo = UserInfoProxy.getInstance().getLoginInfo();
		presenter.loadActiveList(userInfo.getObjectid(), userInfo.userMd5);
	}

	// 创建地理编码检索实例

	protected void sendMessage(String title, String date, String address,
			String hn) {

		SharedPreferences sharedPreferences1 = getActivity()
				.getSharedPreferences("PushMessageId", Context.MODE_PRIVATE);
		int infoId = sharedPreferences1.getInt("PushMessageBeanId", 0);

		PushMessageBean info = new PushMessageBean();
		info.setId("" + infoId);
		info.setTitle(title + "报警");
		info.setDesc(address);
		info.setHn(hn);
		info.setDate(date);
		info.setHid(userInfo.holdid);
		pushMessageDao.create(info);

		SharedPreferences sharedPreferences = getActivity()
				.getSharedPreferences("PushMessageId",
						Context.MODE_WORLD_READABLE);
		Editor editor = sharedPreferences.edit();
		editor.putInt("PushMessageBeanId", ++infoId);
		editor.commit();

		GPSLMainActivity m = GPSLMainActivity.getMainInstance();
		if (m != null) {
			m.refreshDataShow();
		}
	}

	private static TabMonitoringFragmentNew monitorFragment;

	public static TabMonitoringFragmentNew getMainInstance() {
		return monitorFragment;
	}

	String GeocoderAddress = "";

	private String goGeocoder(LatLng newLatLng, final int k, final int Range) {
		RequestParams params = new RequestParams();
		params.addQueryStringParameter("lat", newLatLng.latitude + "");
		params.addQueryStringParameter("lng", newLatLng.longitude + "");

		SendHttpUtils sendHttp = new SendHttpUtils();
		TypeToken type = new TypeToken<GeocoderBean>() {
		};
		sendHttp.doRequest("http://api.zdoz.net/geo2loc_2.aspx", params, type,
				new HttpRequestListener<GeocoderBean>() {
					@Override
					public void onSuccess(String result, GeocoderBean t) {
						GeocoderAddress = t.province + t.city + t.district
								+ t.street;

						if (k != 999 & k < Range) {

							SimpleDateFormat sdfAllShow = new SimpleDateFormat(
									"yyyy-MM-dd HH:mm:ss");
							// 保存到消息列表
							sendMessage(alarmTitle.get(k),
									sdfAllShow.format(new Date()),
									GeocoderAddress, alarmList.get(k).hn);
							setAlarm(alarmTitle.get(k), alarmList.get(k).rt, k);
							// 发送Notification通知
							pushNotify(alarmTitle.get(k), alarmList.get(k).rt,
									k);
							Log.i("TAG11",
									"alarmTitle.get(k)" + alarmTitle.get(k)
											+ "alarmList.get(k).rt"
											+ alarmList.get(k).rt + "K:" + k);
						}
					}

					@Override
					public void onFailure(String error) {
						ToastHelper.toast(error);
					}
				});
		return GeocoderAddress;
	}

	/**
	 * 文件名 setAlarm() 功 能:设置报警 参 数：无 返回值：无
	 * */
	private void setAlarm(String title, String rt, int k) {
		isPlayer = 1;
		// 如果IsNotify为false 没有弹出消息框，反之已经弹出
		if (GPSLApp.IsNotify) {

		} else {
			GPSLApp.IsNotify = true;

			// 播放声音
			try {
				player = ring();
				player.start();
			} catch (IOException e) {
				e.printStackTrace();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	private void pushNotify(String type, String date, int i) {

		// 在Android进行通知处理，首先需要重系统哪里获得通知管理器NotificationManager，它是一个系统Service。
		NotificationManager notifyManager = (NotificationManager) getActivity()
				.getSystemService(Context.NOTIFICATION_SERVICE);
		NotificationCompat.Builder builder;
		builder = new NotificationCompat.Builder(getActivity());
		builder.setSmallIcon(R.drawable.ic_launcher)
				.setLargeIcon(
						BitmapFactory.decodeResource(getResources(),
								R.drawable.ic_launcher))
				.setContentTitle(type + "报警").setContentText(date)
				.setTicker("安诺星有新消息").setOngoing(false)
				.setWhen(System.currentTimeMillis())
				.setPriority(Notification.PRIORITY_DEFAULT).setAutoCancel(true);

		// Uri uri = Uri.parse("gpsl://com.anosine.gpsl.android.activity");
		// Intent intent = new Intent("gpsl.schemeurl.activity");
		Intent intent = new Intent(getActivity(), GPSLMainActivity.class);
		intent.putExtra("isShowTabMessage", "ShowTabMessage");
		// 点击Notification跳转到正在运行的activity
		PendingIntent pendingIntent = PendingIntent.getActivity(getActivity(),
				0, intent, PendingIntent.FLAG_UPDATE_CURRENT);// FLAG_CANCEL_CURRENT
		builder.setContentIntent(pendingIntent);
		// http://blog.csdn.net/feng88724/article/details/6259071这个网址可以设置声音循环，震动等等
		Notification notification = builder.build();
		long[] vibrate = { 0, 10000, 10000, 10000, 10000, 10000, 10000 };
		notification.vibrate = vibrate;
		notification.flags |= Notification.FLAG_AUTO_CANCEL; // FLAG_AUTO_CANCEL表明当通知被用户点击时，通知将被清除。
		notification.flags |= Notification.FLAG_NO_CLEAR;
		// 通过通知管理器来发起通知。如果i不同，则增加一个提示
		notifyManager.notify(i, notification);
	}

	// 播放声音文件方法
	private MediaPlayer ring() throws Exception, IOException {
		Uri alert = RingtoneManager
				.getDefaultUri(RingtoneManager.TYPE_RINGTONE);// .TYPE_RINGTONE个人铃声TYPE_NOTIFICATION
		player = new MediaPlayer();
		player.setDataSource(getActivity(), alert);
		final AudioManager audioManager = (AudioManager) getActivity()
				.getSystemService(Context.AUDIO_SERVICE);
		if (audioManager.getStreamVolume(AudioManager.STREAM_NOTIFICATION) != 0) {
			player.setAudioStreamType(AudioManager.STREAM_NOTIFICATION);

			player.setLooping(true);

			player.prepare();

			player.start();

		}

		return player;
	}

	private void sendResetPosition() {

		showPositionRelative();
		initOverlay(mList);
		resetHeartbeatTimer();

	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		mHandler.post(new Runnable() {
			@Override
			public void run() {

				initData();
				// 获取坐标位置，广告信息
				getAdCoordinate();
				sendGetHttpPositon();

			}
		});
	}

	private Marker[] mMarkerCar, mMarkerCarTitle;
	BitmapDescriptor bd;
	LatLng[] latLng;
	private MapStatusUpdate update;
	private LatLng center = new LatLng(38.876397, 115.471542);

	private void showPositionRelative() {
		if (mActive != null) {
			mMvShow.getMap().clear();
			for (int i = 0; i < mList.size(); i++) {
				if (SelectBtn[i]) {
					LatLng ll = mMarker[i].getPosition();
					mInfoWindow = new InfoWindow(view_alert, ll, -47);// listener
					mBmShow.showInfoWindow(mInfoWindow);
				}

			}
			// 初始化车点
			mMarkerCar = new Marker[mActive.size()];
			// 坐标定义 经纬度
			latLng = new LatLng[mActive.size()];
			//
			popMarkerCarTitle = new Marker[mActive.size()];
			//
			if ("".equals(getOid) || getOid == null) {

			} else {

				for (int i = 0; i < mActive.size(); i++) {

					if (getOid.equals(mActive.get(i).oid)) {
						latLng[i] = getGpsToBaidu(new LatLng(
								Double.parseDouble(mActive.get(i).lt),
								Double.parseDouble(mActive.get(i).lo)));
						// 坐标图片
						bd = BitmapDescriptorFactory
								.fromResource(R.drawable.icon_gcoding_min);// 自动添加的地址R.drawable.icon_gcoding_min
						// 坐标点
						OverlayOptions oob = new MarkerOptions()
								.position(latLng[i]).icon(bd)////
								.draggable(true).zIndex(9).anchor(0.5f, 0.5f);//0.5,0.5用于跟中心点重合
						mMarkerCar[i] = (Marker) (mBmShow.addOverlay(oob));
						/////////////////////////////////////////////////////
						carTitle_alert = LayoutInflater.from(getActivity())
								.inflate(R.layout.fragment_monitor_marker_cartitle,
										null);
						TextView name = (TextView) carTitle_alert
								.findViewById(R.id.name);
						name.setText("\t" + mActive.get(i).hn + "\t");
						OverlayOptions oobb = new MarkerOptions()
								.position(latLng[i])
								.icon(BitmapDescriptorFactory
										.fromBitmap(getViewBitmap(carTitle_alert)))
								.zIndex(9).draggable(true).anchor(0.5f, 1.0f);// 1.0
						popMarkerCarTitle[i] = (Marker) (mBmShow
								.addOverlay(oobb));
					} else {
						latLng[i] = getGpsToBaidu(new LatLng(
								Double.parseDouble(mActive.get(i).lt),
								Double.parseDouble(mActive.get(i).lo)));
						// 坐标图片
						bd = BitmapDescriptorFactory
								.fromResource(R.drawable.icon_gcoding_phone);// 自动添加的地址
						// 坐标点
						OverlayOptions oob = new MarkerOptions()
								.position(latLng[i]).icon(bd).zIndex(9)//
								.draggable(true).anchor(0.0f, 0.0f);//
						mMarkerCar[i] = (Marker) (mBmShow.addOverlay(oob));
						/////////////////////////////////////////////////////
						carTitle_alert = LayoutInflater.from(getActivity())
								.inflate(R.layout.fragment_monitor_marker_name,
										null);
						TextView name = (TextView) carTitle_alert
								.findViewById(R.id.name);
						name.setText("\t" + mActive.get(i).hn + "\t");
						OverlayOptions oobb = new MarkerOptions()
								.position(latLng[i])
								.icon(BitmapDescriptorFactory
										.fromBitmap(getViewBitmap(carTitle_alert)))
								.zIndex(9).draggable(true).anchor(0.4f, 1.0f);
						popMarkerCarTitle[i] = (Marker) (mBmShow
								.addOverlay(oobb));
					}

				}

				// // 坐标 经纬度
				// latLng[i] = getGpsToBaidu(new
				// LatLng(Double.parseDouble(mActive
				// .get(i).lt), Double.parseDouble(mActive.get(i).lo)));
				// // 坐标图片
				// bd = BitmapDescriptorFactory
				// .fromResource(R.drawable.icon_gcoding_phone);// 自动添加的地址
				// // 坐标点
				// OverlayOptions oob = new MarkerOptions().position(latLng[i])
				// .icon(bd).zIndex(9).draggable(true).anchor(1.0f, 0.5f);
				// mMarkerCar[i] = (Marker) (mBmShow.addOverlay(oob));
				// /////////////////////////////////////////////////////
				// carTitle_alert = LayoutInflater.from(getActivity()).inflate(
				// R.layout.fragment_monitor_marker_name, null);
				// TextView name = (TextView)
				// carTitle_alert.findViewById(R.id.name);
				// name.setText("\t" + mActive.get(i).hn + "\t");
				// OverlayOptions oobb = new MarkerOptions()
				// .position(latLng[i])
				// .icon(BitmapDescriptorFactory
				// .fromBitmap(getViewBitmap(carTitle_alert))).zIndex(9)
				// .draggable(true).anchor(1.0f, 1.0f);// 1.0
				// popMarkerCarTitle[i] = (Marker) (mBmShow.addOverlay(oobb));
				// /////////////////////////////////////////////////////////
			}

			if (mBDLocation != null) {
				// 设置自定义图标
				BitmapDescriptor mCurrentMarker = BitmapDescriptorFactory
						.fromResource(R.drawable.icon_gcoding_min);
				MyLocationConfiguration.LocationMode mCurrentMode = MyLocationConfiguration.LocationMode.FOLLOWING;// FOLLOWING
				MyLocationConfiguration config = new MyLocationConfiguration(
						mCurrentMode, true, mCurrentMarker);//mCurrentMarker
				
				mBmShow.setMyLocationConfigeration(config);
				if ("".equals(getOid) || getOid == null) {
					// if
					// (UserInfoProxy.getInstance().getLoginInfo().SaveOid!=null)
					// {
					// for (int i = 0; i < mActive.size(); i++) {
					// if
					// ((UserInfoProxy.getInstance().getLoginInfo().SaveOid).equals(mActive.get(i).oid))
					// {
					// // 蓝色定位在此设置 定位定位定位 根据选择设置定位点 如果先默认第一个
					// MyLocationData locData = new MyLocationData.Builder()
					// .accuracy(mBDLocation.getRadius())
					// // 此处设置开发者获取到的方向信息，顺时针0-360
					// .direction(0)
					// .latitude(latLng[i].latitude)
					// .longitude(latLng[i].longitude).build();
					// mBmShow.setMyLocationData(locData);
					// update = MapStatusUpdateFactory
					// .newLatLng(latLng[i]);
					// mBmShow.animateMapStatus(update);
					// GPSLMainActivity.getMainInstance().mBtnView[0].setText(mActive.get(i).hn);
					//
					// break;
					// }
					// }
					// } else {
					// 蓝色定位在此设置 定位定位定位 根据选择设置定位点 如果先默认第一个
					MyLocationData locData = new MyLocationData.Builder()
							.accuracy(mBDLocation.getRadius())
							
							// 此处设置开发者获取到的方向信息，顺时针0-360
							.direction(0).latitude(latLng[0].latitude)
							.longitude(latLng[0].longitude).build();
					mBmShow.setMyLocationData(locData);
					update = MapStatusUpdateFactory.newLatLng(latLng[0]);
					mBmShow.animateMapStatus(update);
					GPSLMainActivity.getMainInstance().mBtnView[0]
							.setText(mActive.get(0).hn);
					// }

				} else {
					for (int i = 0; i < mActive.size(); i++) {
						if (getOid.equals(mActive.get(i).oid)) {
							// 蓝色定位在此设置 定位定位定位 根据选择设置定位点 如果先默认第一个
							MyLocationData locData = new MyLocationData.Builder()
									.accuracy(mBDLocation.getRadius())
									// 此处设置开发者获取到的方向信息，顺时针0-360
									.direction(0).latitude(latLng[i].latitude)
									.longitude(latLng[i].longitude).build();
							mBmShow.setMyLocationData(locData);
							update = MapStatusUpdateFactory
									.newLatLng(latLng[i]);
							mBmShow.animateMapStatus(update);

							GPSLMainActivity.getMainInstance().mBtnView[0]
									.setText(mActive.get(i).hn);

							break;
						}
					}
				}
			}

		}

	}

	@Override
	public void onPause() {
		mMvShow.onPause();
		super.onPause();
		mBmShow.setMyLocationEnabled(false);
		// cancelHeartbeatTimer();
	}

	@Override
	public void onResume() {
		mMvShow.onResume();
		mActive.clear();
		mBmShow.setMyLocationEnabled(true);
		mHandler.post(new Runnable() {
			@Override
			public void run() {
				resetHeartbeatTimer();
				Log.i("TAGTimer", "onResume:resetHeartbeatTimer");
			}
		});

		super.onResume();
	}

	@Override
	public void onDestroy() {
		// 退出时销毁定位
		// mLocClient.stop();
		// 关闭定位图层
		mBmShow.setMyLocationEnabled(false);
		mMvShow.onDestroy();
		mMvShow = null;
		bdA.recycle();
		mActive.clear();
		super.onDestroy();
		// cancelHeartbeatTimer();

	}

	private BDLocation mBDLocation;

	/**
	 * 定位SDK监听函数 BDLocationListener定位请求回调接口
	 */
	public class MyLocationListenner implements BDLocationListener {

		@Override
		public void onReceiveLocation(BDLocation location) {
			// map view 销毁后不在处理新接收的位置
			if (location == null || mMvShow == null)
				return;

			mBDLocation = location;

			mMyLocation = new LatLng(location.getLatitude(),
					location.getLongitude());
			if (isFirstLoc) {
				isFirstLoc = false;
				MapStatusUpdate u = MapStatusUpdateFactory
						.newLatLng(mMyLocation);
				mBmShow.animateMapStatus(u);
			}
			if (location.getLatitude() == 4.9E-324
					|| location.getLatitude() == 0.0) {

			} else {
				// 重新显示中心位置
				showPositionRelative();
				initOverlay(mList);
			}

		}

		public void onReceivePoi(BDLocation poiLocation) {
		}
	}

	// private Timer mHeartbeatTimer;
	// private static int DELAY = 10 * 1000;// 请求http间隔 10秒后
	//
	// // 取消定时器
	// private void cancelHeartbeatTimer() {
	// if (mHeartbeatTimer != null) {
	// mHeartbeatTimer.cancel();
	// mHeartbeatTimer = null;
	// }
	// }
	//
	// // 启动定时器
	// private void startHeartbeatTimer() {
	// cancelHeartbeatTimer();
	// mHeartbeatTimer = null;
	// mHeartbeatTimer = new Timer();
	// mHeartbeatTimer.schedule(new TimerTask() {
	// public void run() {
	// mHeartbeatTimer = null;
	// if (getActivity() != null && !getActivity().isFinishing()
	// && TabMonitoringFragmentNew.this.isVisible()) {
	// Log.i("TAGTimer", "获取数据...");
	// sendGetHttpPositon();
	// }
	// }
	// }, DELAY);
	// }
	//
	// // 复位定时器
	// public void resetHeartbeatTimer() {
	// synchronized (this) {
	// Log.i("TAGTimer", "复位心跳定时器...");
	// // 取消定时器
	// cancelHeartbeatTimer();
	// // 启动定时器
	// startHeartbeatTimer();
	// }
	// }

	// 取消定时器
	private void cancelHeartbeatTimer() {
		ServiceUtil.cancleAlarmManager(getActivity());
	}

	// 启动定时器
	private void startHeartbeatTimer() {
		ServiceUtil.invokeTimerPOIService(getActivity());
	}

	// 复位定时器
	public void resetHeartbeatTimer() {
		synchronized (this) {
			Log.i("TAGTimer", "resetHeartbeatTimer():复位心跳定时器...");
			// 取消定时器
			cancelHeartbeatTimer();
			// 启动定时器
			startHeartbeatTimer();
		}
	}

	List<Active> alarmList = null;
	List<String> alarmTitle = null;

	@Override
	public void setActiveList(ActiveList t) {
		Log.i("TAGTimer", "getList");
		int number = 0;
		if (t != null) {
			number = t.list != null ? t.list.size() : 0;
			if (number > 0) {
				for (int i = 0; i < number; i++) {
					mActive.add(t.list.get(i));
				}
			}
			alarmList = new ArrayList<Active>();
			alarmTitle = new ArrayList<String>();
			for (int n = 0; n < number; n++) {
				mActiveCarBean = t.list.get(n);
				if (mActiveCarBean.alarmstate != null) {
					status = mActiveCarBean.alarmstate;
					String[] features = status.split(",");
					for (int i = 0; i < features.length; i++) {
						if ("电池供电".equals(features[i])
								|| "震动".equals(features[i])
								|| "断电".equals(features[i])
								|| "防盗".equals(features[i])
								|| "停车".equals(features[i])
								|| "sos".equals(features[i])
								|| "进区域".equals(features[i])
								|| "出区域".equals(features[i])
								|| "求援".equals(features[i])) {
							alarmList.add(mActiveCarBean);
							alarmTitle.add(features[i]);
							break;
						} else if ("移动".equals(features[i])
								|| "超速".equals(features[i])) {
							if (mActiveCarBean.lo == "0"
									& mActiveCarBean.lt == "0") {
								break;
							} else {
								alarmList.add(mActiveCarBean);
								alarmTitle.add(features[i]);
								break;
							}
						}
					}

				}
			}
			if (alarmList.size() > 0) {
				String name = "";
				for (int i = 0; i < alarmList.size(); i++) {
					if (i == (alarmList.size() - 1)) {
						name = name + alarmList.get(i).hn;
					} else {
						name = name + alarmList.get(i).hn + "、";
					}
				}
				tv_alarm.setVisibility(View.VISIBLE);
				tv_alarm.setText(name + "车辆正在报警！");
			} else {
				tv_alarm.setVisibility(View.GONE);
			}

			for (int k = 0; k < alarmList.size(); k++) {
				mActiveCarBean = alarmList.get(k);
				double lo = Double.valueOf(mActiveCarBean.lo);
				double lt = Double.valueOf(mActiveCarBean.lt);
				if (lo != 0 && lt != 0) {
					final LatLng myLatLng = getGpsToBaidu(new LatLng(lt, lo));
					String myaddress = goGeocoder(myLatLng, k, alarmList.size());
				}
				if (lo < 1 && lt < 1) {
					return;
				}
			}
			try {
				if (mList != null) {
					initOverlay(mList);
					sendResetPosition();
				}
			} catch (Exception e) {
			}

		}

		if (number <= 0) {
			resetHeartbeatTimer();
		}
	}

}
